// pages/manage/couponOff/history/index.js
const app = getApp();
let utils = require("../../../../utils/util.js");
import { http } from "../../../../utils/request";
Page({

  /**
   * 页面的初始数据
   */
  data: {
      couponList: [],
      pageIndex: 1,
      isLoad: false

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.queryCouponList();
  },

  /** 礼品券核销列表 */
  queryCouponList(){
    let that = this;
    http.requestData("GET","Coupon/GetWriteOffPage",{
      PageIndex: this.data.pageIndex,
      PageSize: 10
    }).then(res=>{
      if(res.Tag=="10"){
        if(res.Data){
          if(that.data.pageIndex==1){
            that.data.couponList = [];
          }
          res.Data.forEach(item=>{
            item.WriteOffDate = utils.formatTime(new Date(item.WriteOffDate));
            that.data.couponList.push(item);
          })
          if(that.data.couponList.length>0){
            that.data.couponList = that.couponResort(that.data.couponList);
          }
          that.setData({
            couponList: that.data.couponList,
            isLoad: res.Data.length<10?true:false
          })
        }
      }else{
        http.showToast(res.Message);
      }
    }).catch(err=>{})
  },

  /** 以日期分组 */
  couponResort(coupons){
    
    let newArr = [];
    coupons.forEach((item,i)=>{
      let index = -1;
      let createTime = item.WriteOffDate.substring(0,10);
      let isExist = newArr.some((newItem,newI)=>{
        // let newCreateTime = newItem.WriteOffDate.substring(0,10)
        if(createTime == newItem.date){
          index = newI;
          return true;
        }
      })
     
      if(!isExist){
        let resArr = [];
        resArr.push(item);
        newArr.push({
          date: createTime,
          list: resArr
        })
      }else{
        newArr[index].list.push(item);
      }

    })

    return newArr
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.isLoad){
      return
    }
    this.setData({
      pageIndex: this.data.pageIndex+1
    })
    this.queryCouponList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})